package com.example.whrdemospringboot.service;

import com.example.whrdemospringboot.DTO.StudentDTO;
import com.example.whrdemospringboot.converter.StudentConverter;
import com.example.whrdemospringboot.dao.Student;
import com.example.whrdemospringboot.dao.StudentRepository;
import jdk.jfr.TransitionTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentRepository studentRepository;

    @Override
    public StudentDTO getStudentById(Long id) {
        return StudentConverter.convertStudent(studentRepository.findById(id).orElseThrow(RuntimeException::new));
    }

    @Override
    public Long addStudent(StudentDTO studentDTO) {
        //查询一下能否进行添加
        List<Student> names = studentRepository.findByName(studentDTO.getName());
        if (!CollectionUtils.isEmpty(names)) {
            throw new IllegalStateException("name:"+ studentDTO.getName()+" is already taken");
        }
        Student student = studentRepository.save(StudentConverter.converStudent(studentDTO));
        return student.getId();
    }

    @Override
    public void deleteStudentById(Long id) {
        //删除之前也要查询
        studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("id:"+ id +" is not found"));
        studentRepository.deleteById(id);

    }

    @Override
    @Transactional
    public StudentDTO updataStudentById(Long id, String name, String email) {
        Student studentInDB = studentRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("id:" + id + " is not found"));

        if(StringUtils.hasLength(name)&& !studentInDB.getName().equals(name)){
            studentInDB.setName(name);
        }
        if(StringUtils.hasLength(email)&& !studentInDB.getEmail().equals(email)){
            studentInDB.setEmail(email);
        }
        Student student = studentRepository.save(studentInDB);
        return StudentConverter.convertStudent(student);

    }
}
